package openase.audio.conversion;

import harmonic.AudioFloatFormatConverter;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.ByteOrder;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

import openase.audio.AudioFormat;
import openase.audio.AudioUtils;


public class AudioConversionUtils {

    public static AudioInputStream getAudioInputStream(File audioFile, AudioFormat targetFormat) throws AudioConversionException {
        try {
            AudioInputStream ais = AudioSystem.getAudioInputStream(audioFile);
            AudioFormat audioBaseFormat = AudioUtils.fromJavaSoundAudioFormat(ais.getFormat());
            AudioFormat decodedFormat = audioBaseFormat.withSigned(true).withSampleSizeInBits(16).withByteOrder(ByteOrder.LITTLE_ENDIAN);
            
            ais = AudioSystem.getAudioInputStream(AudioUtils.asJavaSoundAudioFormat(decodedFormat), ais);
            ais = new AudioFloatFormatConverter().getAudioInputStream(AudioUtils.asJavaSoundAudioFormat(targetFormat), ais);
            
            return ais;
        } catch (IOException ioe) {
            throw new AudioConversionException(ioe);
        } catch (UnsupportedAudioFileException uafe) {
            throw new AudioConversionException(uafe);
        }
    }
    
    public static byte[] readFile(File audioFile, AudioFormat targetFormat) throws AudioConversionException {
        AudioInputStream ais = getAudioInputStream(audioFile, targetFormat);
        
        byte[] data = new byte[8192];
        int bytesRead;

        final ByteArrayOutputStream out = new ByteArrayOutputStream(4096);

        try {
            while ((bytesRead = ais.read(data, 0, data.length)) > -1) {
                out.write(data, 0, bytesRead);
            }
        } catch (IOException e) {
            throw new AudioConversionException(e);
        }

        return out.toByteArray();
    }
    
}
